/*
 * jxSwing Project (2014)
 * 
 * by Denilson Edinaldo Pinto
 * 
 * LGPL
 * Copyright (C) 2014
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.jxSwing.component.dialog;

import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import org.jxSwing.component.button.ExportButton;
import org.jxSwing.component.chooser.DirectoryChooser;
import org.jxSwing.component.panel.BeanTablePanel;
import org.jxSwing.i18n.I18N;
import org.jxUtils.check.CheckUtil;
import org.jxUtils.enumeration.CSVSeparator;
import org.jxUtils.lang.StringUtil;

/**
 * @author Denilson Edinaldo Pinto
 * @porject jxSwing
 * @package org.jxSwing.component.dialog
 * @date 25/03/2014 - 19:52:35
 */
public class TableExportDialog extends Dialog {
	
	private static final long serialVersionUID = -4460868887739930743L;
	
	private final BeanTablePanel<?> table;
	
	private JLabel lblFormat;
	
	private JComboBox<String> cbxFormat;
	
	private ExportButton btnExport;
	
	private JScrollPane scrlpnLog;
	
	private JTextArea txtLog;
	
	private JProgressBar progressBar;
	
	/**
	 * Create the dialog.
	 * 
	 * @param owner
	 * @param table
	 */
	public TableExportDialog(final Frame owner, final BeanTablePanel<?> table) {
	
		super(owner, true);
		
		this.table = table;
		
		initGUI();
	}
	
	/**
	 * @param fileExtension
	 */
	private void exportTo(final String fileExtension) {
	
		//
		final String tblTitle = CheckUtil.isNullOrAbsoluteEmpty(getTable().getTitle()) ? "" : getTable().getTitle().trim();
		
		// Obtém o nome do Arquivo
		final String fileNameAux = JOptionPane.showInputDialog(I18N.component().fileName() + ":", tblTitle);
		
		// Remove tudo que não é Letra, Número e Espaço
		final String fileName = CheckUtil.isNotNullAndNotAbsoluteEmpty(fileNameAux) ? StringUtil.removePunctuation(StringUtil.normalize(fileNameAux.trim())) : "";
		
		// Se um Nome Válido foi informado para o Arquivo
		if(CheckUtil.isNotNullAndNotAbsoluteEmpty(fileName)) {
			
			final DirectoryChooser chooser = new DirectoryChooser();
			
			chooser.setDialogTitle(I18N.component().exportDirectory());
			chooser.setAcceptAllFileFilterUsed(true);
			chooser.setMultiSelectionEnabled(false);
			
			//
			if(chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
				
				getProgressBar().setIndeterminate(true);
				getTxtLog().setForeground(Color.BLACK);
				getTxtLog().setText(I18N.component().exportingTo(fileExtension.toUpperCase()));
				
				//
				new Thread(new Runnable() {
					
					@Override
					public void run() {
					
						try {
							//
							final File fileResult = new File(chooser.getSelectedFile(), fileName + "." + fileExtension.toLowerCase());
							
							//
							if(fileExtension.trim().equalsIgnoreCase("csv")) {
								
								getTable().toCSV(fileResult, CSVSeparator.SEMI_COLON);
								
							}else if(fileExtension.trim().equalsIgnoreCase("gif")) {
								
								getTable().toGIF(fileResult);
								
							}else if(fileExtension.trim().equalsIgnoreCase("html")) {
								
								getTable().toHTML(fileResult);
								
							}else if(fileExtension.trim().equalsIgnoreCase("jpg")) {
								
								getTable().toJPG(fileResult);
								
							}else if(fileExtension.trim().equalsIgnoreCase("json")) {
								
								getTable().toJSON(fileResult);
								
							}else if(fileExtension.trim().equalsIgnoreCase("png")) {
								
								getTable().toPNG(fileResult);
								
							}else if(fileExtension.trim().equalsIgnoreCase("xls")) {
								
								getTable().toXLS(fileResult);
								
							}else if(fileExtension.trim().equalsIgnoreCase("xml")) {
								
								getTable().toXML(fileResult);
							}
							
							//
							getTxtLog().setText(fileExtension.toUpperCase() + " " + I18N.component().exportedSuccessfully() + ".");
							
							getProgressBar().setIndeterminate(false);
							
							//
							if(JOptionPane.showConfirmDialog(null, I18N.component().wantToOpenTheFile()) == JOptionPane.YES_OPTION) {
								
								Desktop.getDesktop().open(fileResult);
							}
							
							//
							dispose();
							
						}catch(final Throwable throwable) {
							
							getProgressBar().setIndeterminate(false);
							
							throwable.printStackTrace();
							
							getTxtLog().setForeground(Color.RED);
							getTxtLog().setText(I18N.component().error() + ": " + throwable.getMessage());
							
							ExceptionDialog.showMessage(throwable);
						}
					}
				}).start();
			}
		}
	}
	
	/**
	 * @return the btnExport
	 */
	private ExportButton getBtnExport() {
	
		if(btnExport == null) {
			btnExport = new ExportButton();
			btnExport.setEnabled(false);
			btnExport.setBounds(225, 40, 205, 25);
			btnExport.setText(btnExport.getToolTipText());
			btnExport.addActionListener(new ActionListener() {
				
				public void actionPerformed(ActionEvent actionEvent) {
				
					//
					exportTo(getCbxFormat().getSelectedItem().toString());
				}
			});
		}
		return btnExport;
	}
	
	/**
	 * @return the cbxFormat
	 */
	private JComboBox<String> getCbxFormat() {
	
		if(cbxFormat == null) {
			cbxFormat = new JComboBox<>();
			cbxFormat.setModel(new DefaultComboBoxModel<>(new String[]{"", "CVS", "HTML", "JPG", "JSON", "PNG", "XLS", "XML"}));
			cbxFormat.setBounds(10, 40, 205, 25);
			cbxFormat.addItemListener(new ItemListener() {
				
				public void itemStateChanged(ItemEvent itemEvent) {
				
					getBtnExport().setEnabled( !itemEvent.getItem().equals(""));
				}
			});
		}
		return cbxFormat;
	}
	
	/**
	 * @return the lblFormat
	 */
	private JLabel getLblFormat() {
	
		if(lblFormat == null) {
			lblFormat = new JLabel("Formato:");
			lblFormat.setBounds(10, 10, 420, 25);
		}
		return lblFormat;
	}
	
	/**
	 * @return the progressBar
	 */
	private JProgressBar getProgressBar() {
	
		if(progressBar == null) {
			progressBar = new JProgressBar();
			progressBar.setBounds(10, 150, 420, 15);
			progressBar.setPreferredSize(new Dimension(400, 15));
		}
		return progressBar;
	}
	
	/**
	 * @return the scrlpnLog
	 */
	private JScrollPane getScrlpnLog() {
	
		if(scrlpnLog == null) {
			scrlpnLog = new JScrollPane();
			scrlpnLog.setBounds(10, 75, 420, 65);
			scrlpnLog.setViewportView(getTxtLog());
		}
		return scrlpnLog;
	}
	
	/**
	 * @return the table
	 */
	private BeanTablePanel<?> getTable() {
	
		return table;
	}
	
	/**
	 * @return the txtLog
	 */
	private JTextArea getTxtLog() {
	
		if(txtLog == null) {
			txtLog = new JTextArea(I18N.component().chooseFormatForExporting());
			txtLog.setFont(new Font("Dialog", Font.BOLD | Font.ITALIC, 16));
			txtLog.setLineWrap(true);
			txtLog.setEditable(false);
		}
		return txtLog;
	}
	
	/**
	 * 
	 */
	private void initGUI() {
	
		getContentPane().setLayout(null);
		getContentPane().add(getLblFormat());
		getContentPane().add(getCbxFormat());
		getContentPane().add(getBtnExport());
		getContentPane().add(getScrlpnLog());
		getContentPane().add(getProgressBar());
		
		//
		if(getOwner() != null && !getOwner().getIconImages().isEmpty()) {
			
			setIconImage(getOwner().getIconImages().get(0));
			
		}else {
			
			setIconImage(getTable().getOwnerWindowIcon());
		}
		
		setTitle(I18N.component().export());
		setBounds(100, 100, 450, 200);
		setResizable(false);
		centralize();
	}
}
